<template>
  <div class="book-manage">
    <LoadingWrapper :loading="loading">
      <div class="filter-bar-wrapper">
        <FilterBar
          :searchQuery="searchQuery"
          :status="status"
          showSearch
          showStatus
          @update:searchQuery="searchQuery = $event"
          @update:status="status = $event"
        />
      </div>

      <div>
        <el-tabs v-model="activeTab">
          <el-tab-pane label="全部" name="all">
            <el-table 
              v-if="filteredBooks.length > 0"
              :data="paginatedBooks"
              style="width: 100%" 
              :cell-style="{ padding: '12px 0' }"
            >
              <el-table-column 
                prop="index" 
                label="序号" 
                width="80"
                align="center"
              />
              
              <el-table-column 
                prop="title" 
                label="书名" 
                min-width="180"
                align="center"
                show-overflow-tooltip
              />
              
              <el-table-column 
                prop="author" 
                label="作者" 
                min-width="120"
                align="center"
                show-overflow-tooltip
              />
              
              <el-table-column 
                prop="tags" 
                label="标签" 
                min-width="150"
                align="center"
              >
                <template #default="scope">
                  <el-tag
                    v-for="tag in scope.row.tags ? scope.row.tags.split(/\s+/).filter(tag => tag) : []"
                    :key="tag"
                    size="small"
                    class="mx-1"
                  >
                    {{ tag }}
                  </el-tag>
                </template>
              </el-table-column>

            <el-table-column 
              prop="like_count" 
              label="点赞数" 
              width="100"
              align="center"
            /> 

            <el-table-column 
              prop="nickname" 
              label="发布者" 
              width="120"
              align="center"
              show-overflow-tooltip
            />
            
            <el-table-column 
              prop="status" 
              label="状态" 
              width="100"
              align="center"
            >
              <template #default="scope">
                <el-tag 
                  :type="scope.row.status === 1 ? 'success' : 'info'"
                  size="small"
                >
                  {{ scope.row.status === 1 ? '已发布' : '已下架' }}
                </el-tag>
              </template>
            </el-table-column>

            <el-table-column 
              prop="created_at" 
              label="发布时间" 
              width="180"
              align="center"
            >
              <template #default="scope">
                {{ new Date(scope.row.created_at).toLocaleString() }}
              </template>
            </el-table-column>
            
            <el-table-column 
              label="操作" 
              width="120"
              fixed="right"
              align="center"
            >
              <template #default="{ row }">
                <div class="operation-cell">
                  <el-tooltip :content="row.status === 0 ? '上架' : '下架'" placement="top">
                    <el-button
                      :type="row.status === 0 ? 'success' : 'warning'"
                      link
                      @click="row.status === 0 ? handlePublish(row) : handleUnpublish(row)"
                    >
                      <el-icon>
                        <Upload v-if="row.status === 0" />
                        <Download v-else />
                      </el-icon>
                    </el-button>
                  </el-tooltip>

                  <el-tooltip content="删除" placement="top">
                    <el-button 
                      type="danger" 
                      link 
                      @click="handleDelete(row)"
                    >
                      <el-icon><Delete /></el-icon>
                    </el-button>
                  </el-tooltip>
                </div>
              </template>
            </el-table-column>
          </el-table>
          <el-empty v-else description="暂无数据" />
        </el-tab-pane>
      </el-tabs>
    </div>
    </LoadingWrapper>

    <div class="pagination-wrapper">
      <PaginationBar
        v-if="filteredBooks.length > 0"
        v-model:currentPage="currentPage"
        v-model:pageSize="pageSize"
        :total="filteredBooks.length"
        :pageSizes="[10, 15, 20, 25]"
        @pagination-change="handlePaginationChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import { Delete, Download, Upload } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getBookList, publishBook, unpublishBook, deleteBook } from '@/api/book'
import FilterBar from '@/components/filter/FilterBar.vue'
import PaginationBar from '@/components/pagination/PaginationBar.vue'
import LoadingWrapper from '@/components/loading/LoadingWrapper.vue'
import { formatDateTime } from '@/utils/format'

const activeTab = ref('all')
const bookList = ref([])
const searchQuery = ref('')
const status = ref('1') // '1'表示全部，'2'表示已上架，'0'表示已下架
const loading = ref(true)

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)

// 过滤书籍列表
const filteredBooks = computed(() => {
  return bookList.value.filter(book => {
    // 标题或作者名称匹配搜索关键词
    const matchQuery = !searchQuery.value || 
      book.title.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
      book.author.toLowerCase().includes(searchQuery.value.toLowerCase())
    
    // 状态筛选逻辑
    const matchStatus = status.value === '1' || 
      (status.value === '2' && book.status === 1) || 
      (status.value === '0' && book.status === 0)
    
    return matchQuery && matchStatus
  })
})

// 分页后的书籍列表
const paginatedBooks = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredBooks.value.slice(start, end)
})

// 获取书籍列表
const getAllBookList = async () => {
  try {
    loading.value = true
    const res = await getBookList()
    if (res.code === 200) {
      bookList.value = res.data.map((item, index) => ({
        ...item,
        index: index + 1
      }))
    }
  } catch (error) {
    console.error('获取书籍列表失败:', error)
    ElMessage.error('获取书籍列表失败')
  } finally {
    loading.value = false
  }
}

// 上架书籍
const handlePublish = async (row) => {
  try {
    await publishBook(row.id)
    // 更新书籍状态
    row.status = 1
    ElMessage.success('上架成功')
  } catch (error) {
    console.error('上架失败:', error)
    ElMessage.error(error.message || '上架失败，请稍后重试')
  }
}

// 下架书籍
const handleUnpublish = async (row) => {
  try {
    await unpublishBook(row.id)
    // 更新书籍状态
    row.status = 0
    ElMessage.success('下架成功')
  } catch (error) {
    console.error('下架失败:', error)
    ElMessage.error(error.message || '下架失败，请稍后重试')
  }
}

// 删除处理
const handleDelete = async (row) => {
  try {
    await deleteBook(row.id)
    ElMessage.success('删除成功')
    // 重新获取列表
    getAllBookList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '删除失败')
    }
  }
}

// 处理分页变化
const handlePaginationChange = ({ type, value }) => {
  if (type === 'page') {
    currentPage.value = value
  } else if (type === 'size') {
    pageSize.value = value
    currentPage.value = 1
  }
}

// 监听筛选条件变化，重置页码
watch([searchQuery, status], () => {
  currentPage.value = 1
})

// 初始化
onMounted(() => {
  getAllBookList()
})
</script>

<style scoped>
.book-manage {
  padding: 20px;
}

.filter-bar-wrapper {
  display: flex;
  justify-content: flex-end;
}

.operation-cell {
  display: flex;
  justify-content: center;
  gap: 6px;
}

:deep(.el-tag) {
  margin: 0 4px;
}

.el-icon {
  font-size: 18px;
}

:deep(.el-button) {
  padding: 0;
}

.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.pagination-wrapper :deep(.el-pagination) {
  display: flex;
  justify-content: flex-end;
}
</style>